/**
 * @program: yygh_parent
 * @ClassName ScheduleServiceImpl
 * @description:
 * @author: zyw
 * @create: 2023-05-25 13:00
 * @Version 1.0
 **/
package com.atguigu.yygh.hosp.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.yygh.common.exception.YyghException;
import com.atguigu.yygh.hosp.repository.ScheduleRepository;
import com.atguigu.yygh.hosp.service.DepartmentService;
import com.atguigu.yygh.hosp.service.HospitalService;
import com.atguigu.yygh.hosp.service.ScheduleService;
import com.atguigu.yygh.model.hosp.BookingRule;
import com.atguigu.yygh.model.hosp.Department;
import com.atguigu.yygh.model.hosp.Hospital;
import com.atguigu.yygh.model.hosp.Schedule;
import com.atguigu.yygh.vo.hosp.BookingScheduleRuleVo;
import com.atguigu.yygh.vo.hosp.ScheduleOrderVo;
import com.baomidou.mybatisplus.core.metadata.IPage;
import org.joda.time.DateTime;
import org.joda.time.DateTimeConstants;
import org.joda.time.format.DateTimeFormat;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class ScheduleServiceImpl implements ScheduleService {
    @Autowired
    private ScheduleRepository scheduleRepository;
    @Autowired
    private MongoTemplate mongoTemplate;
    @Autowired
    private HospitalService hospitalService;

    @Autowired
    private DepartmentService departmentService;

    @Override
    public void saveSchedule(Map<String, Object> map) {
        String s = JSONObject.toJSONString(map);
        Schedule schedule = JSONObject.parseObject(s, Schedule.class);
        //根据医院编号和排班编号查询
        Schedule existSchedule = scheduleRepository.
                getScheduleByHoscodeAndDepcodeAndHosScheduleId(schedule.getHoscode(), schedule.getDepcode(), schedule.getHosScheduleId());
        if (existSchedule != null) {
            schedule.setCreateTime(existSchedule.getCreateTime());
            schedule.setUpdateTime(new Date());
            schedule.setId(existSchedule.getId());
            schedule.setIsDeleted(0);
        } else {
            schedule.setCreateTime(new Date());
            schedule.setUpdateTime(new Date());
            schedule.setIsDeleted(0);
        }
        scheduleRepository.save(schedule);
    }

    @Override
    public Page<Schedule> getSchedulePage(Map<String, Object> paramMap) {
        Schedule schedule = new Schedule();
        String hoscode = (String) paramMap.get("hoscode");
        schedule.setHoscode(hoscode);
        Example<Schedule> example = Example.of(schedule);
        int pageNum = Integer.parseInt((String) paramMap.get("page"));
        int pageSize = Integer.parseInt((String) paramMap.get("limit"));
        Pageable pageRequest = PageRequest.of(pageNum - 1, pageSize, Sort.Direction.DESC, "createTime");
        Page<Schedule> page = scheduleRepository.findAll(example, pageRequest);
        return page;
    }

    @Override
    public void remove(Map<String, Object> map) {
        String hoscode = (String) map.get("hoscode");
        String hosScheduleId = (String) map.get("hosScheduleId");
        Schedule schedule = scheduleRepository.getScheduleByHoscodeAndHosScheduleId(hoscode, hosScheduleId);
        if (schedule != null) {
            scheduleRepository.deleteById(schedule.getId());
        }
    }

    @Override
    public Map<String, Object> page(long page, long limit, String hoscode, String depcode) {
        //1、根据医院编号和科室编号查询
        Criteria criteria = Criteria.where("hoscode").is(hoscode).and("depcode").is(depcode);
        //2、根据工作日进行分组聚合
        Aggregation agg = Aggregation.newAggregation(
                Aggregation.match(criteria),
                Aggregation.group("workDate")
                        .first("workDate").as("workDate")
                        .count().as("docCount")
                        .sum("reservedNumber").as("reservedNumber")
                        .sum("availableNumber").as("availableNumber"),
                Aggregation.sort(Sort.Direction.ASC, "workDate"),
                //分页
                Aggregation.skip((page - 1) * limit),
                Aggregation.limit(limit)
        );
        //执行
        AggregationResults<BookingScheduleRuleVo> aggregate = mongoTemplate.aggregate(agg, Schedule.class, BookingScheduleRuleVo.class);
        List<BookingScheduleRuleVo> bookingScheduleRuleVos = aggregate.getMappedResults();
        //分组查询总记录数
        Aggregation totalAgg = Aggregation.newAggregation(
                Aggregation.match(criteria),
                Aggregation.group("workDate")
        );
        AggregationResults<BookingScheduleRuleVo> aggregate1 = mongoTemplate.aggregate(totalAgg, Schedule.class, BookingScheduleRuleVo.class);
        int total = aggregate1.getMappedResults().size();
        //将日期与星期进行转换
        for (BookingScheduleRuleVo bookingScheduleRuleVo : bookingScheduleRuleVos) {
            Date workDate = bookingScheduleRuleVo.getWorkDate();
            String dayOfWeek = this.getDayOfWeek(new DateTime(workDate));
            bookingScheduleRuleVo.setDayOfWeek(dayOfWeek);
        }
        HashMap<String, Object> map = new HashMap<>();
        map.put("bookingScheduleRuleList", bookingScheduleRuleVos);
        map.put("total", total);
        //获取医院名称
        Hospital hospital = hospitalService.getByHoscode(hoscode);
        //基础数据
        HashMap<String, String> baseMap = new HashMap<>();
        baseMap.put("hosname", hospital.getHosname());
        map.put("baseMap", baseMap);
        return map;
    }

    @Override
    public List<Schedule> getScheduleDetail(String hoscode, String depcode, String workDate) {
        Date date = new DateTime(workDate).toDate();
        List<Schedule> scheduleList = scheduleRepository.findByHoscodeAndDepcodeAndWorkDate(hoscode, depcode, date);
        scheduleList.stream().forEach(
                item->{
                    this.packageSchedule(item);
                }
        );
        return scheduleList;
    }
    @Override
    public Map<String, Object> getBookingScheduleRule(String hoscode, String depcode, Integer pageNum, Integer pageSize) {
        // 存储结果的HashMap
        HashMap<String, Object> result = new HashMap<>();
        // 根据医院编码获取医院信息
        Hospital hospital = hospitalService.getByHoscode(hoscode);
        if (null == hospital) {
            throw new YyghException();
        }

        // 获取医院的预约规则
        BookingRule bookingRule = hospital.getBookingRule();

        // 获取可预约日期的分页数据
        IPage<Date> iPage = this.getListDate(pageNum, pageSize, bookingRule);
        List<Date> dateList = iPage.getRecords();

        // 构建查询条件，获取可预约日期科室的剩余预约数
        Criteria criteria = Criteria.where("hoscode").is(hoscode)
                .and("depcode").is(depcode)
                .and("workDate").in(dateList);

        // 构建聚合查询，计算预约日期科室的统计信息
        Aggregation agg = Aggregation.newAggregation(
                Aggregation.match(criteria),
                Aggregation.group("workDate")
                        .first("workDate").as("workDate")
                        .count().as("docCount")
                        .sum("availableNumber").as("availableNumber")
                        .sum("reservedNumber").as("reservedNumber"),
                Aggregation.sort(Sort.Direction.ASC,"workDate")
        );

        // 执行聚合查询
        AggregationResults<BookingScheduleRuleVo> aggregationResults = mongoTemplate.aggregate(agg, Schedule.class, BookingScheduleRuleVo.class);
        List<BookingScheduleRuleVo> ruleVoList = aggregationResults.getMappedResults();

        // 将查询结果转换为Map，以便后续快速查找
        Map<Date, BookingScheduleRuleVo> scheduleVoMap = new HashMap<>();
        if (!CollectionUtils.isEmpty(ruleVoList)) {
            scheduleVoMap = ruleVoList.stream().collect(Collectors.toMap(BookingScheduleRuleVo::getWorkDate, BookingScheduleRuleVo -> BookingScheduleRuleVo));
        }

        // 构建可预约排班规则列表
        List<BookingScheduleRuleVo> bookingScheduleRuleVos = new ArrayList<>();
        int len = dateList.size();
        for (int i = 0; i < len; i++) {
            Date date = dateList.get(i);
            BookingScheduleRuleVo bookingScheduleRuleVo = scheduleVoMap.get(date);

            if (bookingScheduleRuleVo == null) {
                // 如果没有查询到预约规则，创建一个新的空规则对象
                bookingScheduleRuleVo = new BookingScheduleRuleVo();
                bookingScheduleRuleVo.setDocCount(0);
                bookingScheduleRuleVo.setAvailableNumber(-1);
            }
            bookingScheduleRuleVo.setWorkDate(date);
            bookingScheduleRuleVo.setWorkDateMd(date);
            String dayOfWeek = this.getDayOfWeek(new DateTime(date));
            bookingScheduleRuleVo.setDayOfWeek(dayOfWeek);

            if (i == len - 1 && pageNum == iPage.getPages()) {
                // 如果是最后一页，则设置状态为1（标识最后一页）
                bookingScheduleRuleVo.setStatus(1);
            } else {
                bookingScheduleRuleVo.setStatus(0);
            }

            if (i == 0 && pageNum == 1) {
                // 如果是第一页，并且当前时间已经超过了停号时间，则设置状态为-1（停止预约）
                DateTime stopTime = this.getDateTime(new Date(), bookingRule.getStopTime());
                if (stopTime.isBeforeNow()) {
                    bookingScheduleRuleVo.setStatus(-1);
                }
            }
            bookingScheduleRuleVos.add(bookingScheduleRuleVo);
        }

        // 构建结果数据
        result.put("bookingScheduleList", bookingScheduleRuleVos);
        result.put("total", iPage.getTotal());

        // 其他基础数据
        Map<String, String> baseMap = new HashMap<>();

        // 医院名称
        baseMap.put("hosname", hospitalService.getByHoscode(hoscode).getHosname());

        // 科室信息
        Department department = departmentService.getDepartment(hoscode, depcode);

        // 大科室名称
        baseMap.put("bigname", department.getBigname());

        // 科室名称
        baseMap.put("depname", department.getDepname());

        // 月份
        baseMap.put("workDateString", new DateTime().toString("yyyy年MM月"));

        // 放号时间
        baseMap.put("releaseTime", bookingRule.getReleaseTime());

        // 停号时间
        baseMap.put("stopTime", bookingRule.getStopTime());

        result.put("baseMap", baseMap);

        return result;
    }

    @Override
    public Schedule getSchedule(String scheduleId) {
        Schedule schedule = scheduleRepository.findById(scheduleId).get();
        this.packageSchedule(schedule);
        return schedule;
    }

    @Override
    public boolean updateAvailableNumber(String scheduleId, Integer availableNumber) {
        Schedule schedule = scheduleRepository.findById(scheduleId).get();
        schedule.setAvailableNumber(availableNumber);
        schedule.setUpdateTime(new Date());
        scheduleRepository.save(schedule);
        return true;
    }

    @Override
    public void cancelSchedule(String scheduleId) {
        Schedule schedule=scheduleRepository.findByHosScheduleId(scheduleId);
        schedule.setAvailableNumber(schedule.getAvailableNumber() + 1);
        scheduleRepository.save(schedule);
    }

    @Override
    public ScheduleOrderVo getScheduleById(String scheduleId) {
        Schedule schedule = scheduleRepository.findById(scheduleId).get();
        ScheduleOrderVo scheduleOrderVo = new ScheduleOrderVo();
        BeanUtils.copyProperties(schedule, scheduleOrderVo);
        Hospital hospital = hospitalService.getByHoscode(schedule.getHoscode());
        scheduleOrderVo.setHosname(hospital.getHosname());
        Department department = departmentService.getDepartment(schedule.getHoscode(), schedule.getDepcode());
        scheduleOrderVo.setDepname(department.getDepname());
        scheduleOrderVo.setReserveDate(schedule.getWorkDate());
        scheduleOrderVo.setReserveTime(schedule.getWorkTime());

        Integer quitDay = hospital.getBookingRule().getQuitDay();
        DateTime quitTime = this.getDateTime(new DateTime(schedule.getWorkDate()).plus(quitDay).toDate(),
                hospital.getBookingRule().getQuitTime());
        DateTime startTime = this.getDateTime(new Date(),
                hospital.getBookingRule().getReleaseTime());
        scheduleOrderVo.setStartTime(startTime.toDate());
        scheduleOrderVo.setQuitTime(quitTime.toDate());

        DateTime stopTime = this.getDateTime(schedule.getWorkDate(),
                hospital.getBookingRule().getStopTime());
        scheduleOrderVo.setStopTime(stopTime.toDate());

        return scheduleOrderVo;
    }


    private IPage<Date> getListDate(Integer pageNum, Integer pageSize, BookingRule bookingRule) {
        // 获取预定规则的周期和发布时间
        Integer cycle = bookingRule.getCycle();
        String releaseTime = bookingRule.getReleaseTime();

        // 根据发布时间获取当前日期时间，并判断是否在当前时间之前
        DateTime dateTime = this.getDateTime(new Date(), releaseTime);
        if (dateTime.isBeforeNow()) {
            cycle++; // 如果发布时间已过，则周期加1
        }

        List<Date> list = new ArrayList<>();
        for (Integer i = 0; i < cycle; i++) {
            // 计算日期时间
            DateTime curDateTime = new DateTime().plusDays(i);
            String dateStr = curDateTime.toString("yyyy-MM-dd");
            list.add(new DateTime(dateStr).toDate()); // 将日期字符串转换为Date对象，并添加到列表中
        }

        // 计算当前页的起始索引和结束索引
        int start = (pageNum - 1) * pageSize;
        int end = start + pageSize;
        if (end > list.size()) {
            end = list.size();
        }

        // 获取当前页的日期列表
        ArrayList<Date> curPageDateList = new ArrayList<>();
        for (int i = start; i < end; i++) {
            Date date = list.get(i);
            curPageDateList.add(date);
        }
        // 创建日期分页对象
        com.baomidou.mybatisplus.extension.plugins.pagination.Page<Date> page =
                new com.baomidou.mybatisplus.extension.plugins.pagination.Page<>(pageNum, pageSize, list.size());
        page.setRecords(curPageDateList);
        return page;
    }

    /**
     * 将Date日期（yyyy-MM-dd HH:mm）转换为DateTime
     */
    private DateTime getDateTime(Date date, String timeString) {
        String dateTimeString = new DateTime(date).toString("yyyy-MM-dd") + " "+ timeString;
        DateTime dateTime = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm").parseDateTime(dateTimeString);
        return dateTime;
    }

    private void packageSchedule(Schedule item) {
        //设置医院名称
        item.getParam().put("hosname", hospitalService.getByHoscode(item.getHoscode()).getHosname());
        //设置科室名称
        item.getParam().put("depname", departmentService.getDepname(item.getHoscode(), item.getDepcode()));
        //设置日期对应星期
        item.getParam().put("dayOfWeek", this.getDayOfWeek(new DateTime(item.getWorkDate())));
    }

    /**
     * 根据日期获取周几数据
     * @param dateTime
     * @return
     */
    private String getDayOfWeek(DateTime dateTime) {
        String dayOfWeek = "";
        switch (dateTime.getDayOfWeek()) {
            case DateTimeConstants.SUNDAY:
                dayOfWeek = "周日";
                break;
            case DateTimeConstants.MONDAY:
                dayOfWeek = "周一";
                break;
            case DateTimeConstants.TUESDAY:
                dayOfWeek = "周二";
                break;
            case DateTimeConstants.WEDNESDAY:
                dayOfWeek = "周三";
                break;
            case DateTimeConstants.THURSDAY:
                dayOfWeek = "周四";
                break;
            case DateTimeConstants.FRIDAY:
                dayOfWeek = "周五";
                break;
            case DateTimeConstants.SATURDAY:
                dayOfWeek = "周六";
            default:
                break;
        }
        return dayOfWeek;
    }

}
 
